package com.tanhua.server.service.impl;

import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserAvatar;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.Answer;
import com.tanhua.model.dto.AnswerDto;
import com.tanhua.model.mongo.Option;
import com.tanhua.model.mongo.Questions;
import com.tanhua.model.mongo.Report;
import com.tanhua.model.mongo.Questionnaire;
import com.tanhua.model.vo.QuestionnaireVo;
import com.tanhua.model.vo.ReportVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.TestSoulService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/8 0008 下午 6:52
 */
@Service
public class TestSoulServiceImpl implements TestSoulService {

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private QuestionnaireApi questionnaireApi;

    @DubboReference
    private OptionApi optionApi;

    @DubboReference
    private QuestionsApi questionsApi;

    @DubboReference
    private ReportApi reportApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    public TestSoulServiceImpl() {
    }

    //todo
    @Override
    public String save(AnswerDto answerDto) {
        String key = Constants.TESTSOUL_KEY + UserHolder.getUserId();
        Integer star = (Integer) redisTemplate.opsForValue().get(key);

        List<Answer> answers = answerDto.getAnswers();
        List<String> optionIds = answers.stream().map(Answer::getOptionId).collect(Collectors.toList());
        List<String> questionIds = answers.stream().map(Answer::getQuestionId).collect(Collectors.toList());

        List<Option> options = optionApi.findByIds(optionIds);
        Questionnaire questionnaire = questionnaireApi.findByQuestionsId(questionIds.get(0));

        Integer score = 0;
        for (Option option : options) {
            score += option.getPoints();
        }

        Report report = new Report();
        report.setUserId(UserHolder.getUserId());
        report.setScore(score);
        report.setStar(questionnaire.getStar());
        report.setCreated(System.currentTimeMillis());
        report.setLevel(score / 20);

        Report r = reportApi.save(report);

        if (star < r.getStar()) {
            redisTemplate.opsForValue().set(key, r.getStar());
        } else if (star == r.getStar()) {
            redisTemplate.opsForValue().set(key, star + 1);
        } else {
            redisTemplate.opsForValue().set(key, star);
        }
        return String.valueOf(r.getId());
    }

    @Override
    public ReportVo findByReportId(String id) {
        Report report = reportApi.findById(id);

        Integer score = report.getScore();
        ReportVo reportVo = new ReportVo();
        //todo 鉴定结果,维度此处被写死,应当建立关系
        if (score >= 0 & score <= 100) {
            if (score <= 20) {
                reportVo.setConclusion("狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。" +
                        "他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，" +
                        "具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
            } else if (score <= 40) {
                reportVo.setConclusion("猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、" +
                        "较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
            } else if (score <= 60) {
                reportVo.setConclusion("白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。" +
                        "他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
            } else if (score <= 80) {
                reportVo.setConclusion("狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，" +
                        "狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。他们在领导风格及决策上，" +
                        "强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
            } else {
                reportVo.setConclusion("狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。" +
                        "他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，" +
                        "具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
            }
        }
        Map<String, String> map1 = new HashMap<>();
        map1.put("外向", "50");
        Map<String, String> map2 = new HashMap<>();
        map1.put("判断", "60");
        Map<String, String> map3 = new HashMap<>();
        map1.put("抽象", "70");
        Map<String, String> map4 = new HashMap<>();
        map1.put("理性", "80");
        List<Map<String, String>> dimensions = new ArrayList<>();
        dimensions.add(map1);
        dimensions.add(map2);
        dimensions.add(map3);
        dimensions.add(map4);
        reportVo.setDimensions(dimensions);

        List<Report> reports = reportApi.findByLevel(report.getLevel());
        List<Long> ids = reports.stream().map(Report::getUserId).collect(Collectors.toList());
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        List<UserAvatar> avatars = ids.stream().map(userId -> {
            UserAvatar userAvatar = new UserAvatar();
            UserInfo userInfo = map.get(userId);
            userAvatar.setId(userInfo.getId());
            userAvatar.setAvatar(userAvatar.getAvatar());
            return userAvatar;
        }).collect(Collectors.toList());
        reportVo.setSimilarYou(avatars);

        return reportVo;
    }


    @Override
    public List<QuestionnaireVo> findQuestionnaire() {

        String key = Constants.TESTSOUL_KEY + UserHolder.getUserId();
        Integer star = (Integer) redisTemplate.opsForValue().get(key);
        if (star == null) {
            star = 0;
            redisTemplate.opsForValue().set(key,star);
        }

        List<Questionnaire> questionnaires = questionnaireApi.findAll();
        List<QuestionnaireVo> vos = new ArrayList<>();
        for (Questionnaire questionnaire : questionnaires) {
            if (questionnaire.getStar() <= star + 1) {
                questionnaire.setIsLock(0);
            }
            List<Questions> questions = questionsApi.findByQuestionnairesId(questionnaire.getId());
            ObjectId reportId = reportApi.findIdByUserId(UserHolder.getUserId(), star);
            questionnaire.setReportId(reportId);
            QuestionnaireVo vo = QuestionnaireVo.init(questionnaire,questions);
            vos.add(vo);
        }

        return vos;
    }
}
